﻿using Kalman.Extensions;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using Wechat.MiniApp;

namespace QuDao
{
    public static class ImgUtils
    {
        ///// <summary>
        ///// 获取商品分享海报图片
        ///// </summary>
        ///// <param name="appid">小程序AppID</param>
        ///// <param name="recoID">推广账号ID</param>
        ///// <param name="goods">商品信息</param>
        //public static Image GetPosterImageOfGoods(string appid, long recoID, Goods goods)
        //{
        //    var width = 600;  //海报图片宽度
        //    var height = 800; //海报图片高度
        //    var bgImg = new Bitmap(width, height); //海报背景图

        //    using var g = Graphics.FromImage(bgImg);
        //    g.Clear(Color.White); //白色背景

        //    using var goodsImg = Image.FromStream(CreateImageFromUrl(goods.ImageUrl)); //
        //    g.DrawImage(goodsImg, 0, 0, width, width); //绘制商品主图

        //    var rect = new Rectangle(x: 0, y: width, width, 200);
        //    var brush = new SolidBrush(Color.White);
        //    g.FillRectangle(brush, rect); //主图下面绘制一个长方形，放商品信息和小程序码

        //    //rect = new Rectangle(0, 800, 600, 40);
        //    //brush = new SolidBrush(Color.LightGray);
        //    //g.FillRectangle(brush, rect);

        //    var y = 625; //第一行商品名称文字起始y轴位置
        //    var goodsName = goods.GoodsName.CutString(0, 60); //控制商品名称不要超过三行
        //    var ss = SplitByLength(goodsName, 20);
        //    var font = new Font("微软雅黑", 18);
        //    brush = new SolidBrush(Color.FromArgb(0, 0, 0));
        //    for (int i = 0; i < ss.Count; i++)
        //    {
        //        g.DrawString(ss[i], font, brush, 25, y);
        //        y += 32; //商品名称文字换行
        //    }

        //    y += 10; //价格信息行y轴位置
        //    font = new Font("微软雅黑", 24, FontStyle.Bold);
        //    brush = new SolidBrush(Color.Red);
        //    g.DrawString($"￥{goods.MinPrice}", font, brush, 25, y); //绘制销售价格

        //    //if (goods.MarketPrice > goods.Price)
        //    //{
        //    //    font = new Font("微软雅黑", 16, FontStyle.Strikeout);
        //    //    brush = new SolidBrush(Color.Gray);
        //    //    g.DrawString($"￥{goods.MarketPrice}", font, brush, 185, y + 10); //绘制市场价格（划线价）
        //    //}

        //    var model = new WxaCodeUnlimitedModel
        //    {
        //        Scene = $"G-{goods.GoodsID}-{recoID}", //商品详情	G-商品ID-推广员ID
        //        Page = "pages/scanQRCode/index",
        //        Width = 280,
        //        IsHyaline = true,
        //        AutoColor = true
        //    };

        //    var data = WxAppClient.Instance.GetUnlimitedWxaCode(appid, model);
        //    var qrcodeImg = Image.FromStream(new MemoryStream(data));
        //    //var qrcodeImg = CreateImageFromUrl("https://gd1.alicdn.com/imgextra/i3/0/O1CN01QJhQwc1zFmLekuni1_!!0-item_pic.jpg_150x150.jpg");
        //    g.DrawImage(qrcodeImg, 440, 625, 150, 150); //绘制小程序码图片

        //    //font = new Font("微软雅黑", 16);
        //    //brush = new SolidBrush(Color.DarkGray);
        //    //g.DrawString("Kalman为您推荐，请长按二维码失败", font, brush, 30, 810);

        //    //var img = RoundCorners(bgImg, 20, Color.Transparent);
        //    //img.Save($"d:\\tmp\\{DateTime.Now:yyyyMMddHHmmss}.png", ImageFormat.Png);
        //    //bgImg.Save($"d:\\tmp\\{DateTime.Now:yyyyMMddHHmmss}.jpg", ImageFormat.Jpeg);

        //    return bgImg;
        //}

        /// <summary>
        /// 图片圆角处理
        /// </summary>
        /// <param name="img">原始图片</param>
        /// <param name="radius">圆角半径，单位：px</param>
        /// <param name="bgColor">圆角背景颜色</param>
        /// <returns></returns>
        public static Image RoundCorners(Image img, int radius, Color bgColor)
        {
            radius *= 2;
            var roundedImage = new Bitmap(img.Width, img.Height);
            using var g = Graphics.FromImage(roundedImage);
            g.Clear(bgColor);
            g.SmoothingMode = SmoothingMode.AntiAlias;

            var brush = new TextureBrush(img);
            using var gp = new GraphicsPath();
            gp.AddArc(0, 0, radius, radius, 180, 90);
            gp.AddArc(0 + roundedImage.Width - radius, 0, radius, radius, 270, 90);
            gp.AddArc(0 + roundedImage.Width - radius, 0 + roundedImage.Height - radius, radius, radius, 0, 90);
            gp.AddArc(0, 0 + roundedImage.Height - radius, radius, radius, 90, 90);

            g.FillPath(brush, gp);
            //g.CompositingQuality = CompositingQuality.HighSpeed;

            return roundedImage;
        }

        public static Stream CreateImageFromUrl(string url)
        {
            var client = new RestClient();
            var request = new RestRequest(url, Method.GET);
            var data = client.DownloadData(request);

            //if (data.Length < 1000)
            //{
            //    var msg = Encoding.UTF8.GetString(data);
            //    throw new Exception(msg);
            //}

            return new MemoryStream(data);
        }

        /// <summary>
        /// 按指定长度将字符串分割成等长字符串列表
        /// </summary>
        /// <param name="str"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static List<string> SplitByLength(string str, int len)
        {
            int pageSize = len;
            var list = new List<string>();
            var pageCount = (int)Math.Ceiling(1.0 * str.Length / pageSize);
            for (int i = 0; i < pageCount; i++)
            {
                var s = str.Skip(i * pageSize).Take(pageSize).ToArray();
                list.Add(new string(s));
            }
            return list;
        }

    }
}
